package ken.app.helper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.ken.callblock2.tools.KENLog;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.text.TextPaint;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;

public class Helper {

	public static final String folroevveer = "K&C";

	/**
	 * 瀏覽器開啟連結
	 * 
	 * @param activity
	 * @param url
	 */
	public static void browerOpenUrl(Activity activity, String url) {
		Uri uri = Uri.parse(url);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		activity.startActivity(intent);
	}

	/**
	 * This method tells you approximately how many megabytes of heap your app
	 * should use if it wants to be properly respectful of the limits of the
	 * present device.
	 * 
	 * @param activity
	 * @return
	 */
	public static int getMemorySuggestion(Activity activity) {
		ActivityManager am = (ActivityManager) activity.getSystemService(Activity.ACTIVITY_SERVICE);
		return am.getMemoryClass();
	}

	/**
	 * 精确获取屏幕尺寸
	 * 
	 * @param ctx
	 * @return
	 */
	public static double getScreenPhysicalSize(Activity ctx) {
		DisplayMetrics dm = new DisplayMetrics();
		ctx.getWindowManager().getDefaultDisplay().getMetrics(dm);
		double diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels, 2) + Math.pow(dm.heightPixels, 2));
		return diagonalPixels / (160 * dm.density);
	}

	/**
	 * 判断是否是平板（官方用法）
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isTablet(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
	}

	public static Bitmap readBitMap(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.ALPHA_8;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		opt.inJustDecodeBounds = true;
		try {
			BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(opt, true);
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (SecurityException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} catch (NoSuchFieldException e1) {
			e1.printStackTrace();
		}
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		BitmapFactory.decodeStream(is, null, opt);
		opt.inJustDecodeBounds = false;
		// opt.inSampleSize = 2;
		return BitmapFactory.decodeStream(is, null, opt);
	}

	public static Bitmap readBitMapforBG(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.ALPHA_8;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		opt.inJustDecodeBounds = true;
		try {
			BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(opt, true);
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (SecurityException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} catch (NoSuchFieldException e1) {
			e1.printStackTrace();
		}
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		BitmapFactory.decodeStream(is, null, opt);
		opt.inJustDecodeBounds = false;
		opt.inSampleSize = 2;
		return BitmapFactory.decodeStream(is, null, opt);
	}

	public static Bitmap getLocalBitmap(Context con, int resourceId) {
		InputStream inputStream = con.getResources().openRawResource(resourceId);
		return BitmapFactory.decodeStream(inputStream, null, getBitmapOptions(1));
	}

	public static BitmapFactory.Options getBitmapOptions(int scale) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		// options.inPurgeable = true;
		// options.inInputShareable = true;
		options.inPreferredConfig = Bitmap.Config.RGB_565;
		// options.inSampleSize = scale;
		return options;
	}

	public static void ToFullScreen(Activity a) {
		a.requestWindowFeature(Window.FEATURE_NO_TITLE);
		a.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

	}

	public static View GetLayout(Activity a, int res) {
		/*
		 * LinearLayout layout = (LinearLayout) Helper.GetLayout(this,
		 * R.layout.main); TextView txtHello = new TextView(this);
		 * txtHello.setText("���"); layout.addView(txtHello);
		 * 
		 * setContentView(layout);
		 */

		// LayoutInflater inflate =
		// (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LayoutInflater inflate = a.getLayoutInflater();

		return inflate.inflate(res, null);
	}

	/**
	 * 字串轉ResourcesID
	 * 
	 * @param context
	 * @param defType
	 * @param variableName
	 * @return
	 */
	public static int getResId(Context context, String defType, String variableName) {
		try {
			return context.getResources().getIdentifier(variableName, defType, context.getPackageName());
		} catch (Exception e) {
			return -1;
		}

	}

	public static void ChangeLayout(Activity activity) {
		TableLayout layout = new TableLayout(activity);
		layout.setLayoutParams(new TableLayout.LayoutParams(4, 5));

		layout.setPadding(1, 1, 1, 1);

		for (int f = 0; f <= 13; f++) {
			TableRow tr = new TableRow(activity);
			for (int c = 0; c <= 9; c++) {
				Button b = new Button(activity);
				b.setText("" + f + c);
				b.setTextSize(10.0f);
				b.setTextColor(Color.rgb(100, 200, 200));
				// b.setOnClickListener(this);
				tr.addView(b, 30, 30);
			} // for

			layout.addView(tr);
		} // for

		activity.setContentView(layout);
	}

	/**
	 * 取得現在時間 ex.yyyy/MM/dd hh:mm:ss
	 * 
	 * @param datetype
	 * @return
	 */
	public static String getDateTime(String datetype) {
		// SimpleDateFormat sdFormat = new
		// SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
		SimpleDateFormat sdFormat = new SimpleDateFormat(datetype);
		Date date = new Date();
		String strDate = sdFormat.format(date);
		// System.out.println(strDate);
		return strDate;
	}

	/**
	 * show Dialog
	 * 
	 * @param activity
	 * @param title
	 * @param msg
	 */
	public static void ShowMessage(Activity activity, String title, String msg) {
		AlertDialog.Builder dlgAbout = new AlertDialog.Builder(activity);
		dlgAbout.setTitle(title);
		dlgAbout.setMessage(msg);
		dlgAbout.setIcon(android.R.drawable.ic_dialog_info);
		dlgAbout.setCancelable(false);
		dlgAbout.setNeutralButton("確定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub

			}
		});
		dlgAbout.show();
	}

	public static void ShowMessage(Activity a, String title, String msg, int btnamount, String[] btntitle,
			DialogInterface.OnClickListener clicklistenerLeft, DialogInterface.OnClickListener clicklistenerCenter,
			DialogInterface.OnClickListener clicklistenerRight) {
		AlertDialog.Builder MyAlertDialog = new AlertDialog.Builder(a);
		if (title != null || title.equals("")) {
			MyAlertDialog.setTitle(title);
		}
		MyAlertDialog.setMessage(msg);
		// 建立按下按鈕
		// DialogInterface.OnClickListener OkClick = null;
		// if (clicklistener1 != null) { OkClick = clicklistener1; }

		switch (btnamount) {
		case 1:
			MyAlertDialog.setNeutralButton(btntitle[0], clicklistenerLeft);
			break;
		case 2:
			MyAlertDialog.setPositiveButton(btntitle[0], clicklistenerLeft);
			MyAlertDialog.setNegativeButton(btntitle[1], clicklistenerRight);
			break;
		case 3:
			MyAlertDialog.setPositiveButton(btntitle[0], clicklistenerLeft);
			MyAlertDialog.setNeutralButton(btntitle[1], clicklistenerCenter);
			MyAlertDialog.setNegativeButton(btntitle[2], clicklistenerRight);
			break;
		}
		MyAlertDialog.show();
	}

	/**
	 * 檢查網路狀態
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null) {
			return false;
		} else {
			NetworkInfo[] infos = cm.getAllNetworkInfo();
			if (infos != null) {
				for (NetworkInfo networkInfo : infos) {
					if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * 隨機取亂數
	 * 
	 * @param start
	 * @param end
	 * @return
	 */

	public static int getRandom(int start, int end) {
		return (int) (Math.random() * (end - start + 1)) + start;
	}

	public static Bitmap createReflectionBitmap(Bitmap src) {
		int margin = 0;
		int width = src.getWidth();
		int height = src.getHeight();

		Matrix matrix = new Matrix();
		matrix.preScale(1, -1);

		Bitmap reflection;
		reflection = Bitmap.createBitmap(src, 0, height / 2, width, height / 2, matrix, true);

		Bitmap result;
		result = Bitmap.createBitmap(width, height + height / 3, Config.ARGB_8888);
		Canvas canvas;
		canvas = new Canvas(result);

		canvas.drawBitmap(src, 0, 0, null);

		canvas.drawBitmap(reflection, 0, height + margin, null);

		Paint paint = new Paint();

		LinearGradient shader;

		shader = new LinearGradient(0, height, 0, result.getHeight() + margin, 0x90ffffff, 0x00ffffff, TileMode.CLAMP);

		paint.setShader(shader);

		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));

		canvas.drawRect(0, height, width, result.getHeight(), paint);

		return result;
	}

	public static int getScreenWidth(Activity a) {
		DisplayMetrics dm = new DisplayMetrics();
		a.getWindowManager().getDefaultDisplay().getMetrics(dm);

		return dm.widthPixels;
	}

	public static int getScreenHeight(Activity a) {
		DisplayMetrics dm = new DisplayMetrics();
		a.getWindowManager().getDefaultDisplay().getMetrics(dm);

		return dm.heightPixels;
	}

	public static int dip2px(Activity a, float dpValue) {
		final float scale = a.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	public static int px2dip(Activity a, float pxValue) {
		final float scale = a.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	// Returns the index of the first occurrence of the lower or upper specified
	// character a-z
	public static int getFirstAlphaIndex(String toFind) {
		int idx = -1;

		for (int i = 0; i < toFind.length(); i++) {
			if (Character.UnicodeBlock.of(toFind.charAt(i)) == Character.UnicodeBlock.BASIC_LATIN) {
				idx = i;
				break;
			}
		}

		return idx;
	}

	public static String insertString(String origin, int pos, String insert) {
		try {
			return (origin = origin.substring(0, pos) + insert + origin.substring(pos));
		} catch (Exception e) {
			return origin;
		}
	}

	public static String timestampToDate(long timestamp, String yyyyMMdd) {
		// 設定時間格式&時區
		SimpleDateFormat format = new SimpleDateFormat(yyyyMMdd);
		// format.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
		// long b=1335297780;
		// Long d=Long.parseLong(b)*1000;
		Timestamp ts = new Timestamp(timestamp * 1000);
		return format.format(ts);
	}

	/**
	 * 關閉輸入法鍵盤
	 * 
	 * @param context
	 */
	public static void keybordOff(Context context) {

		try {
			InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
			// inputMethodManager.showSoftInput(v,InputMethodManager.SHOW_FORCED);
			boolean isOpen = inputMethodManager.isActive();
			if (isOpen) {
				inputMethodManager.hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	/**
	 * Bitmap转换成InputStream
	 * 
	 * @param bm
	 * @return
	 */
	public static InputStream Bitmap2IS(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		InputStream sbs = new ByteArrayInputStream(baos.toByteArray());
		return sbs;
	}

	/**
	 * inputstream轉byte
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static byte[] getBytes(InputStream is) throws IOException {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int len = 0;

		while ((len = is.read(b, 0, 1024)) != -1) {
			baos.write(b, 0, len);
			baos.flush();
		}
		byte[] bytes = baos.toByteArray();
		return bytes;
	}

	/**
	 * 調整音量
	 * 
	 * @param manager
	 * @param keyCode
	 * @return
	 */
	public static boolean audioVolume(AudioManager manager, int keyCode) {
		if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
			manager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
			manager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
			return true;
		}
		return false;
	}

	/**
	 * 启动APK的默认Activity
	 * 
	 * @param context
	 * @param packageName
	 */

	public static void startApkActivity(final Context context, String packageName) {
		PackageManager pm = context.getPackageManager();
		PackageInfo pi;
		try {
			pi = pm.getPackageInfo(packageName, 0);
			Intent intent = new Intent(Intent.ACTION_MAIN, null);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			intent.setPackage(pi.packageName);

			List<ResolveInfo> apps = pm.queryIntentActivities(intent, 0);

			ResolveInfo ri = apps.iterator().next();
			if (ri != null) {
				String className = ri.activityInfo.name;
				intent.setComponent(new ComponentName(packageName, className));
				context.startActivity(intent);
			}
		} catch (NameNotFoundException e) {
			KENLog.e("startActivity", e.getMessage());
		}
	}

	/**
	 * 计算字宽 注意如果设置了textStyle，还需要进一步设置TextPaint
	 * 
	 * @param text
	 * @param Size
	 * @return
	 */
	public static float GetTextWidth(String text, float Size) {
		TextPaint FontPaint = new TextPaint();
		FontPaint.setTextSize(Size);
		return FontPaint.measureText(text);
	}

	/**
	 * 取得HashKey
	 * 
	 * @param context
	 */
	public static void printHashKey(Context context) {

		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(context.getApplicationContext().getPackageName(),
					PackageManager.GET_SIGNATURES);
			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				KENLog.d("TEMPTAGHASH KEY:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
			}
		} catch (NameNotFoundException e) {

		} catch (NoSuchAlgorithmException e) {

		}

	}
	
	public static String[] split(String s, String token) {
		if (s == null)
			return null;
		if (token == null || s.length() == 0)
			return new String[] { s };
		int size = 0;
		String[] result = new String[4];
		while (s.length() > 0) {
			int index = s.indexOf(token);
			String splitOne = s;
			if (index > -1) {
				splitOne = s.substring(0, index);
				s = s.substring(index + token.length());
			} else {
				s = "";
			}
			if (size >= result.length) {
				String[] tmp = new String[result.length * 2];
				System.arraycopy(result, 0, tmp, 0, result.length);
				result = tmp;
			}
			if (splitOne.length() > 0) {
				result[size++] = splitOne;
			}
		}
		String[] tmp = result;
		result = new String[size];
		System.arraycopy(tmp, 0, result, 0, size);
		return result;
	}

	// //Determine screen size
	// if ((getResources().getConfiguration().screenLayout &
	// Configuration.SCREENLAYOUT_SIZE_MASK) ==
	// Configuration.SCREENLAYOUT_SIZE_LARGE) {
	// Toast.makeText(this, "Large screen",Toast.LENGTH_LONG).show();
	//
	// }
	// else if ((getResources().getConfiguration().screenLayout &
	// Configuration.SCREENLAYOUT_SIZE_MASK) ==
	// Configuration.SCREENLAYOUT_SIZE_NORMAL) {
	// Toast.makeText(this, "Normal sized screen" , Toast.LENGTH_LONG).show();
	//
	// }
	// else if ((getResources().getConfiguration().screenLayout &
	// Configuration.SCREENLAYOUT_SIZE_MASK) ==
	// Configuration.SCREENLAYOUT_SIZE_SMALL) {
	// Toast.makeText(this, "Small sized screen" , Toast.LENGTH_LONG).show();
	// }
	// else {
	// Toast.makeText(this, "Screen size is neither large, normal or small" ,
	// Toast.LENGTH_LONG).show();
	// }
	//
	//
	//
	//
	// //Determine density
	// DisplayMetrics metrics = new DisplayMetrics();
	// getWindowManager().getDefaultDisplay().getMetrics(metrics);
	// int density = metrics.densityDpi;
	//
	// if (density==DisplayMetrics.DENSITY_HIGH) {
	// Toast.makeText(this, "DENSITY_HIGH... Density is " +
	// String.valueOf(density), Toast.LENGTH_LONG).show();
	// }
	// else if (density==DisplayMetrics.DENSITY_MEDIUM) {
	// Toast.makeText(this, "DENSITY_MEDIUM... Density is " +
	// String.valueOf(density), Toast.LENGTH_LONG).show();
	// }
	// else if (density==DisplayMetrics.DENSITY_LOW) {
	// Toast.makeText(this, "DENSITY_LOW... Density is " +
	// String.valueOf(density), Toast.LENGTH_LONG).show();
	// }
	// else {
	// Toast.makeText(this,
	// "Density is neither HIGH, MEDIUM OR LOW.  Density is " +
	// String.valueOf(density), Toast.LENGTH_LONG).show();
	// }
}
